<?php
namespace Weixin\Controller;
use Think\Controller;
use Weixin\ORG\Session;
ini_set('session.gc_maxlifetime', 24 * 3600);
session_start();

/**
 * Created by PhpStorm.
 * Author: wcj
 * Date: 2016/10/22
 * Time: 00:35
 */
class GetInfoController extends Controller
{
    //微信授权跳转
    public function index()
    {
        $appId = C('APP_ID');
        $redirect_uri = "http://www.justwkj.xyz/index.php/Weixin/GetInfo/callback";
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . $appId . "&redirect_uri=" . $redirect_uri . "&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";
        redirect($url);
    }
    public function callback(){
        $code = $_GET["code"];
        $returnUrl = "http://" . $_SERVER['HTTP_HOST'];
        if ($code == "") {
            echo "none";
            exit;
        }
        $appId = C('APP_ID');
        $appSecret = C('APP_SECRET');
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $appId . "&secret=" . $appSecret . "&code=" . $code . "&grant_type=authorization_code";
        $data = "";
        $tmpInfo = $this->vpost($url, $data);
        $j_arr = json_decode($tmpInfo, true);
        $openid = $j_arr["openid"];
        $access_token = $j_arr["access_token"];
        $refresh_token = $j_arr["refresh_token"];
        $url2 = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $access_token . "&openid=" . $openid . "&lang=zh_CN";
        $tmpInfo2 = $this->vpost($url2, $data);
        $u2_arr = json_decode($tmpInfo2, true);
        $nickname = $u2_arr["nickname"];
        $openid = $u2_arr["openid"];
        $headimgurl = str_replace("wx.qlogo.cn/mmopen/", "", str_replace("http://", "", $u2_arr["headimgurl"]));
        $sex = $u2_arr["sex"];
        $province = $u2_arr["province"];
        $city = $u2_arr["city"];
        $country = $u2_arr["country"];
        header("Location:http://www.justwkj.xyz/index.php/Weixin/GetInfo/getInfo?openid=" . $openid . "&nickname=" . $nickname . "&headimgurl=" . $headimgurl . "&sex=" . $sex . "&province=" . $province . "&city=" . $city . "&country=" . $country);
    }

    // 模拟提交数据函数
    function vpost($url, $data){   
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE); // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)'); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        $tmpInfo = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            echo 'Errno' . curl_error($curl);//捕抓异常
        }
        curl_close($curl); // 关闭CURL会话

        return $tmpInfo; // 返回数据
    }

//授权后保存用户信息
    public function getInfo(){
        if(isset($_GET['openid'])){
            $user['openid'] = $_GET['openid'];
            $user['nickname'] = $_GET['nickname'];
            $user['imgurl'] = $_GET['headimgurl'];
            $user['sex'] = $_GET['sex'];
            $user['province'] = $_GET['province'];
            $user['city'] = $_GET['city'];
            $user['country'] = $_GET['country'];
            $user['overdue_time'] = time() + 300 * 24 * 3600;//目前没有用到，这个字段用于判断这个权登录的过期时间，如果超出了这个时间，直接跳到退出方法，让用户进行重新登录。
            $has = M('wx_user')->where(array('openid' => $user['openid']))->find();
             //当$has为空时，说明是第一次登录，所有是先将值存入到wx_user表中,然后直接跳到登录页面
            if (empty($has)) {
                session('openid',$user['openid']);
                M('wx_user')->add($user);
                echo "<script>location.href='".U("Public/login")." '</script>";
                die();  
            //当$has不为空，且字段work_id为空时，表示，已在微信端登录过，但是安全退出了，所有是直接跳到登录页面        
            }elseif(!empty($has) && empty($has["work_id"])){
                session('openid',$user['openid']);
                echo "<script>location.href='".U("Public/login")." '</script>";
                die();   
            //当$has不为空，且字段work_id不为空时，说明在微信端登录过，且没有安全退出，可以直接省略登录，直接跳到主页面      
            }elseif(!empty($has) && !empty($has["work_id"])){
                $where["mobile"] = $has["work_id"];
                $user = M("user")->where($where)->find();
                if($user){
                    session("user",$user);
                    echo "<script>location.href='".U("Index/index")." '</script>"; //跳转到主页面
                }
                die();        
            }
        }else{
            echo "<SCRIPT language=JavaScript>alert('没有获取到用户信息！');location.href='javascript:history.go(-1);';</SCRIPT>";
            echo ' ';
            exit;
        }
    }
}
